<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="topNav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
        <el-breadcrumb-item>成本调整</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="together-content">
      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :inline="true" label-width="90px" style="width: 100%">
          <el-form-item>
            <el-input
              v-model="searchForm.keyword"
              placeholder="单据号/备注"
              clearable
            />
          </el-form-item>

          <!-- 时间范围选择 -->
          <el-form-item label="日期：">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              style="width: 340px"
              clearable
            />
          </el-form-item>

          <!-- 业务人员 -->
          <el-form-item label="业务人员：">
            <el-select style="width: 200px" v-model="searchForm.staffId">
              <el-option label="请选择" value="" />
              <el-option label="仓库-小衣" value="S1001" />
              <el-option label="仓库-小三" value="S1003" />
              <el-option label="仓库-小五" value="S1005" />
              <el-option label="仓库-小七" value="S1007" />
              <el-option label="仓库-小九" value="S1009" />
            </el-select>
          </el-form-item>

          <!-- 查询按钮 -->
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 分割线 -->
      <el-divider style="margin: 10px 0" />

      <!-- 操作按钮 -->
      <div style="margin-bottom: 15px; text-align: right;">
        <el-button type="primary" size="small" @click="toAddAdjustView()">新增</el-button>
        <el-button type="success" size="small" @click="auditAdjust()">审核</el-button>
        <el-button type="info" size="small" @click="unAuditAdjust()">反审核</el-button>
        <el-button type="danger" size="small" @click="deleteAdjustOrder()">删除</el-button>
      </div>

      <!-- 表格 -->
      <el-table ref="adjustListTable" :data="adjustList" style="width: 100%" border>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="单据编号" width="200" align="center" />
        <el-table-column prop="createdTime" label="创建时间" width="180" align="center" />
        <el-table-column prop="staffName" label="业务人员" width="170" align="center" />
        <el-table-column prop="auditorName" label="审核人员" width="170" align="center" />
        <el-table-column prop="remark" label="备注" min-width="200" align="center" />
        <el-table-column prop="status" label="状态" width="150" align="center">
          <template #default="scope">
            {{ showAdjustStatus(scope.row.status) }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" min-width="180" align="center">
          <template #default="scope">
            <el-button link type="warning" size="small" @click="editRow(scope.row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="deleteRow(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: center;" v-if="pageInfo">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="pageInfo.total"
          @current-change="changePage"
          layout="total, ->, prev, pager, next, jumper"
          background
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

let axios = inject('axios')
let router = useRouter()
let loading = ref(false)

// 快捷时间选择器
const shortcuts = [
  {
    text: '今天',
    value: () => {
      const now = new Date()
      return [new Date(now.getFullYear(), now.getMonth(), now.getDate()), new Date()]
    }
  },
  {
    text: '最近一周',
    value: () => {
      const now = new Date()
      const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
      return [oneWeekAgo, now]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const now = new Date()
      const oneMonthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
      return [oneMonthAgo, now]
    }
  }
]

// 搜索表单
const searchForm = ref({
  keyword: '',
  dateRange: [],
  staffId: ''
})

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const currentPage = ref(1)
const pageInfo = ref(null)

// 成本调整列表
const adjustList = ref([])

// 状态显示
const showAdjustStatus = (status) => {
  switch (status) {
    case 0: return '已打回'
    case 1: return '已创建'
    case 2: return '已提交'
    case 3: return '已审核'
    default: return '未知'
  }
}

// 初始化数据
onMounted(() => {
  onSubmit()
})

// 查询
const onSubmit = () => {
  if (loading.value) return
  loading.value = true

  axios.post('/xyy/costAdjustment/page', {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    keyword: searchForm.value.keyword,
    beginTime: searchForm.value.dateRange ? searchForm.value.dateRange[0] : null,
    endTime: searchForm.value.dateRange ? searchForm.value.dateRange[1] : null,
    staffId: searchForm.value.staffId
  }).then(res => {
    pageInfo.value = res.data.pageInfo
    adjustList.value = res.data.pageInfo ? res.data.pageInfo.list : []
  }).finally(() => {
    loading.value = false
  })
}

// 分页切换
const changePage = (now) => {
  pageNum.value = now
  onSubmit()
}

// 跳转到新增
const toAddAdjustView = () => {
  router.push({ name: 'costEdit' })
}

// 审核
const auditAdjust = () => {
  const selection = ref(this.$refs.adjustListTable).getSelectionRows()
  if (selection.length === 0) {
    ElMessage.warning('请先选择要审核的记录')
    return
  }

  ElMessageBox.confirm(`确定审核选中的 ${selection.length} 条记录吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    // 示例：发送审核请求
    const ids = selection.map(row => row.id)
    axios.post('/xyy/costAdjustment/audit', { ids }).then(() => {
      ElMessage.success('审核成功')
      onSubmit() // 刷新列表
    })
  })
}

// 反审核
const unAuditAdjust = () => {
//   const selection = ref(this.$refs.adjustListTable).getSelectionRows()
//   if (selection.length === 0) {
//     ElMessage.warning('请先选择要反审核的记录')
//     return
//   }

//   ElMessageBox.confirm(`确定反审核选中的 ${selection.length} 条记录吗？`, '提示', {
//     type: 'warning'
//   }).then(() => {
//     const ids = selection.map(row => row.id)
//     axios.post('/xyy/costAdjustment/unAudit', { ids }).then(() => {
//       ElMessage.success('反审核成功')
//       onSubmit()
//     })
//   })
}

// 删除单条
const deleteRow = (index) => {
  ElMessageBox.confirm('确定删除此成本调整单？', '提示', {
    type: 'warning'
  }).then(() => {
    adjustList.value.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 删除选中所有
const deleteAdjustOrder = () => {
  const selection = ref(this.$refs.adjustListTable).getSelectionRows()
  if (selection.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }

  ElMessageBox.confirm(`确定删除选中的 ${selection.length} 条记录？`, '提示', {
    type: 'warning'
  }).then(() => {
    selection.forEach(row => {
      const idx = adjustList.value.findIndex(item => item.id === row.id)
      if (idx > -1) adjustList.value.splice(idx, 1)
    })
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 编辑行
const editRow = (row) => {
  router.push({ name: 'costEdit', params: { id: row.id } })
}
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #f9f9f9;
}

.topNav {
  margin-bottom: 20px;
}

.cell-item {
  font-weight: bold;
}

.margin-top {
  margin-top: 10px;
}
</style>